<template>
  <div>
    <el-form :model="supData" label-width="80px" :inline="false">
      <el-form-item label="SPU名称">
        <el-input
          v-model="supData.spuName"
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <template slot-scope="{ row, $index }">
          <el-select placeholder="请选择品牌" v-model="supData.tmId">
            <el-option :label="data.tmName" :value="data.id" v-for="data,index in tabData" :key="index"> </el-option>
          </el-select>
        </template>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input v-model="supData.description" type="textarea" placeholder="描述"
          rows="4"></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <template slot-scope="{ row, $index }">
          <el-upload
            action="/dev-api/admin/product/fileUpload"
            list-type="picture-card"
            :file-list="imgData"
            :on-success='upLoadImg'
            :on-remove="RmoveLoadImg"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </template>
      </el-form-item>
      <el-form-item label="销售属性">
        <template slot-scope="{ row, $index }">
          <el-select :placeholder="slectNum" v-model="attr">
            <el-option :label="data.name" :value="`${data.id}+${data.name}`" v-for="data,index in slectData" :key="index"> </el-option>
          </el-select>
          <el-button
            type="primary"
            size="default"
            icon="el-icon-circle-plus"
            style="margin: 0px 10px"
            :disabled='!attr'
            @click="pushList"
            >
            添加销售属性
          </el-button>
        </template>
      </el-form-item>
      <el-form-item>
        <el-table :data="supData.spuSaleAttrList" border stripe>
        <el-table-column type="index" label="序号" :width="80">
        </el-table-column>
        <el-table-column label="属性名" prop="saleAttrName" :width="150"> </el-table-column>
        <el-table-column label="属性名称列表" width="width" prop="spuSaleAttrValueList">
            <template slot-scope="{row,$index}">
                <el-tag type="warning" v-for="data,index in row.spuSaleAttrValueList" :disable-transitions="false"   @close="row.spuSaleAttrValueList.splice(index,1)" :key='index' closable style="margin:0px 5px">{{data.saleAttrValueName}}</el-tag>
                <el-input
                    :ref='$index'
                    class="input-new-tag"
                    v-show="row.flag"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(row,$index)"
                    @blur="handleInputConfirm(row,$index)"
                    v-model="strdata"
                ></el-input>
                <el-button v-show="!row.flag" class="button-new-tag" size="small" @click="showInput(row,$index)">+ 添加</el-button>
            </template>
        </el-table-column>
        <el-table-column label="操作" :width="100">
            <template slot-scope="{row,$index}" >
                <el-button type="danger" @click="supData.spuSaleAttrList.splice($index,1)" >
                    删除
                </el-button>
            </template>
            </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="saveData">保存</el-button>
        <el-button @click="changeSpuDisplay(0)">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
name: "Spuform",
data() {
    return {
    model:'',
    strdata:'',
    listData:[],
    tabData: [],
    imgData:[],
    supData:{
            category3Id: 0,//三级id
            description: "", //描述
            tmId: "",//平台的id
            spuName: "",
            spuImageList: [],
            spuSaleAttrList: [],
    },
    attr:'',
    dialogImageUrl: "",
    dialogVisible: false,
    };
},
props:['listDisplay'],
watch:{
    listDisplay(newVlue){
        if(newVlue !== 1){
            // this.supData = {
            // category3Id: 0,//三级id
            // description: "", //描述
            // tmId: "",//平台的id
            // spuName: "",
            // spuImageList: [],
            // spuSaleAttrList: [],
            // }
            // this.imgData=[]
            // this.listData =[]
            // this.tabData =[]
            Object.assign(this._data,this.$options.data()) //数据初始化
        }
    }
},
computed:{
    slectNum(){
        return this.slectData.length > 0? `还有${this.slectData.length}个属性可选`:'暂无其他属性'
    },
    slectData(){
        let result = []
        if(this.supData.spuSaleAttrList){
            result = this.listData.filter(name=>{
            let key = true;
            this.supData.spuSaleAttrList.map(eve =>{
                if(eve.saleAttrName == name.name){
                    key = false
                }
            })
            return key
        })
        }
        return result.length > 0 ? result : this.listData
    }
},
methods: {
    async saveData(){
        this.supData.spuImageList = this.imgData.map(name=>{
            return{
                imgName:name.name,
                imgUrl:(name.response && name.response.data)||name.imgUrl
            }
        })
        const result = await this.$API.spu.reqSpuInfo(this.supData)
        this.$message.error*'保存失败请重试'
        if(result.code == 200){
            await this.$bus.$emit('getDataList',this.supData.id ? undefined:1)
            this.$message.success('保存成功')
            this.changeSpuDisplay(0)
            return true
        }
        this.$message.error('保存出错了'+result.data)
    },
    handleInputConfirm(row,index) {
        let arr = this.supData.spuSaleAttrList[index].spuSaleAttrValueList.filter(name=>{
            return name.saleAttrValueName == this.strdata
        })
        if(this.strdata.trim()!=''&& arr.length == 0&&this.strdata.length < 10){
            this.supData.spuSaleAttrList[index].spuSaleAttrValueList.push({
            saleAttrName:row.saleAttrName,
            baseSaleAttrId:row.baseSaleAttrId,
            saleAttrValueName:this.strdata
        })
        }else if(this.strdata.trim()==''){
            this.$message.warning('请勿输入违规字符')
        }else if(arr.length != 0){
            this.$message.warning('请勿重复输入字符')
        }else{
            this.$message.warning('字符长度过长,合法字符长度应小于10')
        }
        this.strdata = ''
        row.flag = false;
        // this.inputValue = '';
    },
    showInput(row,index) {
        row.flag = true
        this.$nextTick(function(){
            this.$refs[index].focus()
        })
        
    },
    pushList(){
        let [baseSaleAttrId,saleAttrName] = this.attr.split("+")
        if(this.supData.spuSaleAttrList){
            this.supData.spuSaleAttrList.push({
            baseSaleAttrId,saleAttrName,
            spuSaleAttrValueList:[],
            flag:false
        })
        }
        // this.$nextTick(function(){
        //     this.$refs[this.supData.spuSaleAttrList.length - 1].focus()
        // })
        this.attr = ''
    },
    RmoveLoadImg(_,fileList){
        this.imgData = fileList;
    },
    upLoadImg(_,_$,fileList){
        this.imgData = fileList
    },
    handleClose(tag1,tag2,index){
       
    },
    //通知父组件改变状态
    changeSpuDisplay(shape) {
        this.$bus.$emit("changeSpuDisplay", shape);
    },
    //异步请求和数据处理
    async getSpuMsg(row){
        if(this.listDisplay === 1){
            try {    
            this.model = false  
            let result = {code:200}
            let imgResult = {code:200}
            if(row){
                this.model = true
                result = await this.$API.spu.reqSpuMsg(row.id)
                imgResult = await this.$API.spu.reqSpuimg(row.id)
            }
            const listResult = await this.$API.spu.reqSpuList()
            const AttributeResult = await this.$API.spu.reqAllAttribute()
            const arr = [result,listResult,imgResult,AttributeResult]
            let key = true;
            let dowkey = true;
            let str = ''
            arr.map(name=>{
                if(name.code !== 200){
                    str += '--'+name.data+'---',
                    key = false
                }
                if(!name.message){
                    dowkey = false
                }
            })
            if(key){
                this.$message.success('数据请求成功')
                if(dowkey){
                    let img  = imgResult.data   
                    img.forEach(element => {
                        element.name= element.imgName
                        element.url = element.imgUrl
                    });
                    result.data.spuSaleAttrList.forEach(value=>{
                        value.flag = false
                    })
                    this.supData = result.data
                    this.imgData = img
                    this.updata = result.data
                }
                this.listData = AttributeResult.data
                this.tabData = listResult.data
            }else{
                this.$message.error('发送成功了但是问题是'+str)
            }
        } catch (error) {
            this.$message.error(`请求出错了，理由是: ${error}`)
        }
        }
    },
    },
};
</script>

<style>
.el-tag + .el-tag {
    margin-left: 10px;
}
.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}
.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
</style>